﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.Ptoduction;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.SCWorkCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.SCWorkCommandHandler
{
    public class SCWorkOrderAddCommandHandler : IRequestHandler<SCWorkOrderAddCommand, APIResult<object>>
    {

        /// <summary>
        /// 基本信息仓储接口
        /// </summary>
        private readonly IBaseRepository<ProductionWorkOrderBasicInfoSheet> jRepo;
        /// <summary>
        /// 物品仓出接口
        /// </summary>
        private readonly IBaseRepository<ProductionItem> wRepo;
        /// <summary>
        /// 公益流程仓储接口
        /// </summary>
        private readonly IBaseRepository<ProcessFlowSheet> lRepo;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        public SCWorkOrderAddCommandHandler(IBaseRepository<ProductionWorkOrderBasicInfoSheet> jRepo, IBaseRepository<ProductionItem> wRepo, IBaseRepository<ProcessFlowSheet> lRepo, IMapper mapper)
        {
            this.jRepo = jRepo;
            this.wRepo = wRepo;
            this.lRepo = lRepo;
            this.mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(SCWorkOrderAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
                // 先处理物品信息表
                ProductionItem pr = new ProductionItem
                {
                    itemName = request.itemName,
                    itemNumber = request.itemNumber,
                    specification = request.specification,
                    unit = request.unit,
                    itemCategory = request.itemCategory,
                    itemClassification = request.itemClassification,
                    plannedStartTime = request.plannedStartTime,
                    plannedEndTime = request.plannedEndTime,
                    plannedOutput = request.plannedOutput
                };
                int w = await wRepo.AddAsync(pr);
                if (w <= 0)
                {
                    result.Code = APIEnums.添加失败;
                    result.Msg = APIEnums.添加失败.ToString();
                    return result;
                }
                // 处理基本信息表
                ProductionWorkOrderBasicInfoSheet p = new ProductionWorkOrderBasicInfoSheet
                {
                    WorkOrderName = request.WorkOrderName,
                    WorkOrderNumber = request.WorkOrderNumber,
                    AssociatedProductionOrderNumber = request.AssociatedProductionOrderNumber,
                    SalesOrder = request.SalesOrder,
                    AssociatedProject = request.AssociatedProject,
                    WorkOrderDate = request.WorkOrderDate,
                    PersoninCharge = request.PersoninCharge,
                    AffiliatedDepartment = request.AffiliatedDepartment,
                    Remarks = request.Remarks,
                    WenJian = request.WenJian,
                    CreateName = "任昱卫",
                    CreateTime = DateTime.Now,
                    ProductionItemId = pr.ProductionItemId, // pr 已保存，Id 有效
                    ProcessFlowSheetId = pr.ProductionItemId
                };
                int j = await jRepo.AddAsync(p);
                if (j <= 0)
                {
                    result.Code = APIEnums.添加失败;
                    result.Msg = "添加失败";
                    result.data = j;
                    return result;
                }

                // 处理工序流程表
                if (request.processFlowSheets != null && request.processFlowSheets.Any())
                {
                    foreach (var x in request.processFlowSheets)
                    {
                        x.ProcessFlowSheetId = p.ProcessFlowSheetId ?? 0; // 若 p.ProcessFlowSheetId 不为 null，取其值；否则取 0
                    }
                    int l = await lRepo.AddRanges(request.processFlowSheets);
                    if (l <= 0)
                    {
                        result.Code = APIEnums.添加失败;
                        result.Msg = APIEnums.添加失败.ToString();
                    }
                    else
                    {
                        result.Code = APIEnums.添加成功;
                        result.Msg = APIEnums.添加成功.ToString();
                    }
                }
                else
                {
                    result.Code = APIEnums.添加成功;
                    result.Msg = APIEnums.添加成功.ToString(); // 允许流程表为空
                }
            }
            catch (Exception ex)
            {
                result.Code = APIEnums.添加失败;
                result.Msg = $"添加失败: {ex.Message}";
            }
            return result;
        }
    }
}
    

